package com.ffapp.f9164.td.user;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.BleLog;
import com.clj.fastble.utils.HexUtil;
import com.ffapp.f9164.td.BuildConfig;
import com.ffapp.f9164.td.R;
import com.ffapp.f9164.td.basis.Constants;
import com.ffapp.f9164.td.bean.DevTypeCfg;
import com.ffapp.f9164.td.eventbus.PopHandleMessage;
import com.ffapp.f9164.td.home.HomeBaseActivity;
import com.ffapp.f9164.td.login.LoginActivity;
import com.ffapp.f9164.td.util.SubstringUtil;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.leon.lfilepickerlibrary.LFilePicker;
import com.leon.lfilepickerlibrary.utils.Constant;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import my.ActivityTool;
import my.BleUtils;
import my.DialogUtils;
import my.FileUtils;
import my.IntentUtils;
import my.MySharedPreferences;


public class UserIndexActivity extends HomeBaseActivity {

    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.tv_device_name)
    TextView tvDeviceName;
    @BindView(R.id.tv_app_code)
    TextView tvAppCode;

    private boolean isFinish = false;

    private Handler sendAtHandle = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 76:  //检查是否传输完毕
                    if(!isFinish){
                        showToast("指令失败，请重试");
                        dismissProgress();
                        BleUtils.stopNotify();
                    }
                    break;
            }
        }
    };


    @Override
    public void initViews() {
        setContentView(R.layout.user_index_activity);
        super.initViews();
        setTitleBg(R.color.transparent);
        tvAppCode.setText(""+BuildConfig.VERSION_CODE);
    }



    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        MySharedPreferences mSp = new MySharedPreferences(this);
        tvVersion.setText("当前连接设备" );
//        tvDeviceName.setText("当前连接设备" + mSp.getDevType());
        tvDeviceName.setText(mSp.getDevType());
    }


    @Override
    protected void onResume() {
        super.onResume();
//        getImmersionBar().statusBarDarkFont(true,0.5f);
        getImmersionBar().statusBarDarkFont(true).init();
        isFront = true;
    }
    private boolean isFront = false;
    @Override
    protected void onPause() {
        super.onPause();
        isFront = false;
    }

    @OnClick(R.id.btn_out)
    void logout() {
        DialogUtils.DialogTwo(mContext, "", "退出当前账号？", "立即退出", "取消", new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                LoginActivity.isLogin = false;
                LoginActivity.toLoadingAllClear(mContext);
            }
        }, null);
    }



    @OnClick({R.id.btn_refresh, R.id.view_version, R.id.view_modifypwd, R.id.view_bugly, R.id.view_restart, R.id.btn_out, R.id.view_about})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_refresh:
                break;
            case R.id.view_version:
                showToast("开发中....");
//                PopHandle popHandle = new PopHandle(mContext, "connect_fail");
//                popHandle.show();
                break;
            case R.id.view_modifypwd:
                ActivityTool.skipActivity(mContext,WareSoftUpdateActivity.class);
                break;
            case R.id.view_about:
                ActivityTool.skipActivity(mContext,AboutActivity.class);
                break;
            case R.id.view_bugly:
                new LFilePicker()
                        .withActivity(UserIndexActivity.this)
                        .withRequestCode(REQUEST_BUGLY_SHARE)
                        .withTitle("文件选择")
                        .withBackgroundColor("#0396FF")
                        .withMutilyMode(false)
                        .withMaxNum(1)
                        .withStartPath(Constants.DIR_DEBUG)//指定初始显示路径
                        .withFileFilter(new String[]{"txt", "docx"})
                        .start();
                break;
            case R.id.view_restart:
                break;
            case R.id.btn_out:
                break;
        }
    }


    private final static int REQUEST_BUGLY_SHARE = 41;    //从日志文件夹返回

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ( requestCode == REQUEST_BUGLY_SHARE  && resultCode == Activity.RESULT_OK) {//是否选择，没选择就不会继续
            String path = null;
            List<String> list = data.getStringArrayListExtra(Constant.RESULT_INFO);
            if(list == null || list.size() == 0){
            }else {
                path = list.get(0);
            }
            if(TextUtils.isEmpty(path)){
                DialogUtils.DialogOkMsg(mContext,"读取文档失败");
                return;
            }
            shareOrOpen(path);
        }

    }

    public void  shareOrOpen(final String path){
        DialogUtils.DialogStringList(mContext, new String[]{"查看", "分享"}, new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(position == 0){
                    FileUtils.openFile(new File(path),mContext);
                }else {
                    IntentUtils.doShareFile(mContext,path);
                }
            }
        });
    }


    @OnClick(R.id.view_reset)
    public void reset(){

        DialogUtils.DialogTwo(mContext, "", "是否恢复出厂设置？", "是", "取消", new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                isFinish = false;
                BleUtils.notify(new BleNotifyCallback() {
                    @Override
                    public void onNotifySuccess() {

                        BleUtils.write(HexUtil.strToHex("AT+FACTORY"), new BleWriteCallback() {
                            @Override
                            public void onWriteSuccess(final int current, final int total, final byte[] justWrite) {
                                showLoading();
                                if (current == total) {
                                    BleLog.d("下发设置发送成功");
                                    Message message = new Message();
                                    message.what = 2;
                                    //这时候可以做30秒的计时操作
                                    sendAtHandle.sendEmptyMessageDelayed(Constants.CHECK_FINISH, 20000);
                                }
                            }

                            @Override
                            public void onWriteFailure(final BleException exception) {
                                BleLog.d("下发设置发送失败");
                            }
                        });

                    }

                    @Override
                    public void onNotifyFailure(BleException exception) {
                        BleLog.d("下发设置打开通知操作失败");
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        isFinish = true;
                        dismissProgress();
                        showToast("恢复出厂成功");
                        BleUtils.stopNotify();
                    }

                    @Override
                    public void onError() {
                        dismissProgress();
                        showToast("恢复出厂失败");
                        BleUtils.stopNotify();
                    }
                });
            }
        },null);
    }


    @OnClick(R.id.view_restart)
    public void restart(){

        DialogUtils.DialogTwo(mContext, "", "是否重启设备？", "立即重启", "取消", new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                isFinish = false;
                showToast("正在重启设备");
                BleUtils.notify(new BleNotifyCallback() {
                    @Override
                    public void onNotifySuccess() {

                        BleUtils.write(HexUtil.strToHex("AT+RESET"), new BleWriteCallback() {
                            @Override
                            public void onWriteSuccess(final int current, final int total, final byte[] justWrite) {
                                showLoading();
                                if (current == total) {
                                    BleLog.d("下发设置发送成功");
                                    Message message = new Message();
                                    message.what = 2;
                                    //这时候可以做30秒的计时操作
                                    sendAtHandle.sendEmptyMessageDelayed(Constants.CHECK_FINISH, 20000);
                                }
                            }

                            @Override
                            public void onWriteFailure(final BleException exception) {
                                BleLog.d("下发设置发送失败");
                            }
                        });

                    }

                    @Override
                    public void onNotifyFailure(BleException exception) {
                        BleLog.d("下发设置打开通知操作失败");
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        isFinish = true;
                        dismissProgress();
                        showToast("重启设备完成");
                        BleUtils.stopNotify();
                    }

                    @Override
                    public void onError() {
                        dismissProgress();
                        showToast("重启设备失败");
                        BleUtils.stopNotify();
                    }
                });
            }
        },null);

    }

    @Override
    public void onMessageEvent(PopHandleMessage event) {
        super.onMessageEvent(event);
        BleLog.d("onDisConnected =PopHandleMessage=="+event.message);
        if(isFront ){
            BleUtils.reConnect(mContext, new BleUtils.BleUtilLoginCallBack() {
                @Override
                public void isLogin(boolean isSuccess,String message) {
                    showToast(""+message);
                    dismissProgress();
                }
            });
        }
    }

}
